package org.s3.project.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import lombok.extern.slf4j.Slf4j;
import org.s3.project.entity.Orders;
import org.s3.project.service.OrdersService;
import org.s3.project.util.AliPayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/alipay")
@Slf4j
public class AliPayController {

    @Autowired
    private AlipayClient alipayClient;
    @Autowired
    private AliPayConfig aliPayConfig;
    @Autowired
    private OrdersService ordersService;


    @GetMapping("/pay")
    public String alipay(String OrdersNumber,HttpServletResponse response) throws IOException, AlipayApiException {
        System.out.println(OrdersNumber);
        // 实例化客户端,填入所需参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        // 在公共参数中设置回跳和通知地址
    // 设置支付宝返回页面URL，用户支付成功后将被重定向到此URL
        request.setReturnUrl(aliPayConfig.getRETURN_URL());
    // 设置支付宝服务器异步通知页面路径，支付宝会在此路径下发送POST请求通知支付结果
        request.setNotifyUrl(aliPayConfig.getNOTIFY_URL());
    // 获取当前时间
//        Date date = new Date();
    // 创建日期格式化对象，用于生成唯一订单号，格式为：年月日时分秒毫秒
//        SimpleDateFormat orderIdFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        // 生成订单号
//        String orderId = orderIdFormat.format(date);
    // 调用服务层方法创建订单，参数包括：
    // - 订单号（基于当前时间生成）
    // - 用户ID
    // - 场次ID
    // - 位置信息
    // - 票价
    // - 座位ID
//        orderinfoService.buyTickets(orderId, userId, schedule_id, position, price, seatId);
    // 打印新增订单的日志信息
        System.out.println("新增订单！");
        // 根据订单编号,查询订单相关信息
        System.out.println("查询订单！");
            Orders byId = ordersService.getByOrdersNumber(OrdersNumber);
        request.setBizContent("{\"out_trade_no\":\"" + byId.getNumber() + "\","
                + "\"total_amount\":\"" + byId.getAmount() + "\","
                + "\"subject\":\"" + "买电影票" + "\","
                + "\"body\":\"" + byId.getRemark() + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单

        return form;
    }

    // 处理支付宝通知的GET请求
    @GetMapping(value = "/notify")
    public void returnUrl(HttpServletRequest request, HttpServletResponse response) throws IOException, AlipayApiException {
        request.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        System.out.println("1");
        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        System.out.println("params = " + params);
        // 从请求中获取参数
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 解决乱码问题
            valueStr = new String(valueStr.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
            params.put(name, valueStr);
        }
        System.out.println(params);// 查看参数都有哪些
        // 调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, aliPayConfig.getALIPAY_PUBLIC_KEY(), aliPayConfig.getCHARSET(), aliPayConfig.getSIGN_TYPE());
        System.out.println("signVerified = " + signVerified);
        // 验证签名通过
        if (!signVerified) {
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            System.out.println("商户订单号 = " + out_trade_no);
            System.out.println("支付宝交易号 = " + trade_no);
            System.out.println("付款金额 = " + total_amount);
            // 支付成功，修改支付状态
            System.out.println("修改状态！");
            ordersService.updState(out_trade_no);
            // 重定向到支付状态页面
            response.sendRedirect("http://127.0.0.1:8848/front-endccc/waimai/ok.html");
        } else {
            // 如果签名验证失败，也可以重定向到支付状态页面
            response.sendRedirect("http://127.0.0.1:8848/zhifu.html");
        }
    }
}
